package net.flowas.modulecart.rest;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import net.flowas.modulecart.domain.Category;

/**
 * 
 */
//@Path("/categories")
public class CategoryEndpoint
{
   private EntityManager em= Persistence.createEntityManagerFactory ("cartPU").createEntityManager();

   @POST
   @Consumes("application/json")
   public Category create(Category entity)
   {
      em.persist(entity);
      //URI ff = UriBuilder.fromResource(CategoryEndpoint.class).path(String.valueOf(entity.getId())).build();
      return entity;
   }

   @DELETE
   @Path("/{id:[0-9][0-9]*}")
   public Response deleteById(@PathParam("id") Long id)
   {
      Category entity = em.find(Category.class, id);
      if (entity == null)
      {
         return Response.status(Status.NOT_FOUND).build();
      }
      em.remove(entity);
      return Response.noContent().build();
   }

   @GET
   @Path("/{id:[0-9][0-9]*}")
   @Produces("application/json")
   public Response findById(@PathParam("id") Long id)
   {
      TypedQuery<Category> findByIdQuery = em.createQuery("SELECT DISTINCT c FROM Category c LEFT JOIN FETCH c.parent LEFT JOIN FETCH c.children WHERE c.id = :entityId ORDER BY c.id", Category.class);
      findByIdQuery.setParameter("entityId", id);
      Category entity;
      try
      {
         entity = findByIdQuery.getSingleResult();
      }
      catch (NoResultException nre)
      {
         entity = null;
      }
      if (entity == null)
      {
         return Response.status(Status.NOT_FOUND).build();
      }
      return Response.ok(entity).build();
   }

   @GET
   @Path("list.json")
   @Produces("application/json")
   public List<Category> listAll(@QueryParam("start") Integer startPosition, @QueryParam("max") Integer maxResult)
   {
      TypedQuery<Category> findAllQuery = em.createQuery("SELECT DISTINCT c FROM Category c LEFT JOIN FETCH c.parent LEFT JOIN FETCH c.children ORDER BY c.id", Category.class);
      if (startPosition != null)
      {
         findAllQuery.setFirstResult(startPosition);
      }
      if (maxResult != null)
      {
         findAllQuery.setMaxResults(maxResult);
      }
      final List<Category> results = findAllQuery.getResultList();
      return results;
   }

   @PUT
   @Path("/{id:[0-9][0-9]*}")
   @Consumes("application/json")
   public Response update(Category entity)
   {
      entity = em.merge(entity);
      return Response.noContent().build();
   }
}